import { Request, RequestHandler, Response } from 'express';
import {
  IGetAppropriationByIdReq,
  IAddAppropriationReq,
  IUpdateAppropriationReq,
  IDeleteAppropriationReq
} from '../../models/appropriation.model';
import * as AppropriationService from '../services/appropriation.service';
import { convertToLocalDateString } from '../utils/date';

/**
 * Get active appropriation records
 *
 * @param req Express Request
 * @param res Express Response
 */
export const getAppropriations: RequestHandler = async (req: Request, res: Response) => {
  try {
    const appropriations = await AppropriationService.getAppropriations();

    res.status(200).json({
      data: appropriations,
      code: 2000,
    })
  } catch (error) {
    console.error('[appropriations.controller][getAppropriations][Error] ', typeof error === 'object' ? JSON.stringify(error) : error);
    res.status(500).json({
      message: '经费科目列表获取失败！'
    });
  }
};

/**
 * Get approved appropriation records
 *
 * @param req Express Request
 * @param res Express Response
 */
export const getApprovedAppropriations: RequestHandler = async (req: Request, res: Response) => {
  try {
    const appropriations = await AppropriationService.getApprovedAppropriations();

    res.status(200).json({
      data: appropriations,
      code: 2000,
    })
  } catch (error) {
    console.error('[appropriations.controller][getApprovedAppropriations][Error] ', typeof error === 'object' ? JSON.stringify(error) : error);
    res.status(500).json({
      message: '经费科目列表获取失败！'
    });
  }
};

/**
 * Get appropriation record based on id provided
 *
 * @param req Express Request
 * @param res Express Response
 */
// @ts-ignore
export const getAppropriationById: RequestHandler = async (req: IGetAppropriationByIdReq, res: Response) => {
  try {
    const appropriation = await AppropriationService.getAppropriationById(req.params.id);

    res.status(200).json({
      data: appropriation,
      code: 2000,
    })
  } catch (error) {
    console.error('[appropriations.controller][getAppropriationById][Error] ', typeof error === 'object' ? JSON.stringify(error) : error);
    res.status(500).json({
      message: '经费科目获取失败！'
    });
  }
};

/**
 * Inserts a new appropriation record
 *
 * @param req Express Request
 * @param res Express Response
 */
export const addAppropriation: RequestHandler = async (req: IAddAppropriationReq, res: Response) => {
  try {
    req.body.createdTime = new Date(Date.now());
    req.body.updatedTime = req.body.createdTime;
    const result = await AppropriationService.insertAppropriation(req.body);

    res.status(200).json({
      data: result,
      code: 2000,
    })
  } catch (error) {
    console.error('[appropriations.controller][addAppropriation][Error] ', typeof error === 'object' ? JSON.stringify(error) : error);
    if (error.code === 'ER_DUP_ENTRY') {
        res.status(500).json({
            message: '经费科目名称重复，请重新输入！'
          });
    } else {
        res.status(500).json({
            message: '经费科目保存失败！'
         });
    }
  }
};

/**
 * Updates existing appropriation record
 *
 * @param req Express Request
 * @param res Express Response
 */
// @ts-ignore
export const updateAppropriationById: RequestHandler = async (req: IUpdateAppropriationReq, res: Response) => {
  try {
    req.body.updatedTime = new Date(Date.now());
    req.body.appropriationApproveDate = req.body.appropriationApproveDate
      ? req.body.appropriationApproveDate.length === 10 ?req.body.appropriationApproveDate : convertToLocalDateString(req.body.appropriationApproveDate)
      : null;
    const result = await AppropriationService.updateAppropriation({...req.body, id: req.params.id});

    res.status(200).json({
      data: result,
      code: 2000,
    })
  } catch (error) {
    console.error('[appropriations.controller][updateAppropriationById][Error] ', typeof error === 'object' ? JSON.stringify(error) : error);
    if (error.code === 'ER_DUP_ENTRY') {
        res.status(500).json({
            message: '经费科目名称重复，请重新输入！'
          });
    } else {
        res.status(500).json({
            message: '经费科目更新失败！'
         });
    }
  }
};

/**
 * deletes a appropriation
 *
 * @param req Express Request
 * @param res Express Response
 */
// @ts-ignore
export const deleteAppropriationById: RequestHandler = async (req: IDeleteAppropriationReq, res: Response) => {
  try {
    const result = await AppropriationService.deleteAppropriation(req.params.id);

    res.status(200).json({
      data: result,
      code: 2000,
    })
  } catch (error) {
    console.error('[appropriations.controller][deleteAppropriationById][Error] ', typeof error === 'object' ? JSON.stringify(error) : error);
    res.status(500).json({
      message: '经费科目删除失败！'
    });
  }
};